package com.code;


public class PropertyBuilderOfFloat implements PropertyBuilder {

	@Override
	public short[] buildProperty(int code,int len,String value) {
		short [] floatByte = new short[5];
		floatByte[0]=(short)code;
     	floatByte[1]=ByteUtil.floatToBytes(Double.parseDouble(value))[0];
        floatByte[2]=ByteUtil.floatToBytes(Double.parseDouble(value))[1];
        floatByte[3]=ByteUtil.floatToBytes(Double.parseDouble(value))[2];
        floatByte[4]=ByteUtil.floatToBytes(Double.parseDouble(value))[3];
		return floatByte;
	}

	@Override
	public String translateData(byte[] datas,int len ,int offset) {
		String value = String.valueOf(ByteUtil.bytesToFloat(datas[offset+1],datas[offset+2],datas[offset+3],datas[offset+4]));
		return value;
	}

	@Override
	public String encode(String pvalue, int length) {
		Double object=Double.parseDouble(pvalue);
		float value=((Double) object).floatValue();
		int lvalue=Float.floatToIntBits(value);
		
	    return String.format(formats[length],lvalue);
	}
    private static String[] formats={null,"%02X",null,null,"%08X"};
	@Override
	public String decode(String pdata, int length) {
		Float f=(Float)Float.intBitsToFloat((int)Long.parseLong(pdata,16));
		if (Float.isInfinite(f)) {
			return "-9999.0";
		}
		return f.toString();
	}

	@Override
	public Double parseValue(String pvalue) {
		if ("NaN".equals(pvalue)) return Double.NaN;
		if ("Infinite".equals(pvalue)) return Double.POSITIVE_INFINITY;
		return Double.parseDouble(pvalue);
	}
    public static void  main(String[] args){
    	String pvalue="7F800000";
    	PropertyBuilderOfFloat pb=new PropertyBuilderOfFloat();
    	//Double object=Double.parseDouble(pvalue);
		//float value=((Double) object).floatValue();
    	String pdata=pb.decode(pvalue, 4);
	    System.out.println(pdata);
	    Double value=pb.parseValue(pdata);
	    System.out.println(value);
	    pdata=NumberUtil.decimalFormat(4).format(value);
	    System.out.println(pdata);
	    //System.out.println(((Float)Float.intBitsToFloat((int)Long.parseLong("BDCCCCCD",16))).toString());
    }
}
